//Copyright (c) 2024 Deng Zicheng
//        "CarController" is licensed under Mulan PSL v2.
//        You can use this software according to the terms and conditions of the Mulan PSL v2.
//        You may obtain a copy of Mulan PSL v2 at:
//        http://license.coscl.org.cn/MulanPSL2
//        THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
//        See the Mulan PSL v2 for more details.
import prompt from '@system.prompt';
import Router from '@system.router';
import {MessageData} from "../blueTooth/blueTooth"
import BLE from "../blueTooth/blueTooth"
import Prompt from '@system.prompt';

const ABILITY_TYPE_EXTERNAL = 0;
const ACTION_SYNC = 0;
// const ACTION_MESSAGE_CODE_CALL = 1001;
const ACTION_MESSAGE_CODE_SUBSCRIBE_USER = 1005;
const ACTION_MESSAGE_CODE_UNSUBSCRIBE = 1006;
// const TYPE_SCAN=0;
// const TYPE_DEVICES=1;
// const TYPE_CONNECT=2;
const USER_MOD=1;
const AUTO_MOD=0

export default {
    data: {
        car_init:true,
        comp_init:0,
        RSSI:0,
        degree:0,//角度
        speed_ctrl:0,//速度控制值
        X_diff:33,
        Y_diff:31.5,
        X_orig:83,
        Y_orig:79,
        rocker_X:0,
        rocker_Y:0,
        ap_Y:210,
        ap_Y_orig:210,
        rocker_lock:true,//摇杆锁定标志
        speed_lock:true,//推杆锁定标志
        sign_GO_BACK:true,//go为true
        sign_LEFT_RIGHT:true,//left为true
        power:0,//电量
        connect_state:false,//连接状态
        speed:0,//速度显示数据
        barrier:false,//障碍物标志
        stop_state:false,//停止状态标志
        car_mode_state:false,//车辆模式
        controlIntervalID:null,
    },
    onInit() {
        this.rocker_X=this.X_orig;
        this.rocker_Y=this.Y_orig;
        this.ap_Y=this.ap_Y_orig;
    },
    onShow(){
        this.actionJava("subscribe");//订阅后台服务
        let data=new MessageData();//初始化控制模式数据
        data.option="mod";
        data.code=USER_MOD;
        BLE.actionJava(data);//发送数据
        this.controlIntervalID=setInterval(this.car_control,10);//开启数据上报定时中断
    },
    onHide(){
        clearInterval(this.controlIntervalID);
    },
    onDestroy(){
        this.actionJava("unsubscribe");
    },
    /**
     * 小车初始化提醒
     */
    notice_init(){
        if (!this.car_init&&this.connect_state) {
            Prompt.showDialog({message:"正在开机！"});
            return true;
        }else {
            return false;
        }
    },
    /**
     * 摇杆开始触摸
     * @param e
     */
    rockerStart(e){
        this.notice_init();
        this.rocker_X = e.touches[0].localX-this.X_diff;
        this.rocker_Y = e.touches[0].localY-this.Y_diff;
        this.computeDegree();
    },
    /**
     *  摇杆开始移动
     */
    rockerMove(e){
        let x=e.touches[0].localX-this.X_diff;
        let y=e.touches[0].localY-this.Y_diff;
        this.rocker_X = x
        this.rocker_Y = y
        this.computeDegree();
    },
    /**
     *  摇杆停止触摸
     * @param e
     */
    rockerEnd(){
        if (this.rocker_lock) {
            this.rocker_X =this.X_orig;
            this.rocker_Y =this.Y_orig;
            this.degree=0;
        }
    },
    /**
     * 计算角度
     */
    computeDegree(){
        let  tan_x=this.rocker_X-this.X_orig;
        let tan_y=this.rocker_Y-this.Y_orig;
        this.sign_GO_BACK=(tan_y<0);
        this.sign_LEFT_RIGHT=(tan_x<0)
        let degree=Math.atan(Math.abs(tan_x)/Math.abs(tan_y))/(Math.PI/2)*90
        if (degree == NaN) {
            degree=0;
        }
        if (tan_x < 0) {
            this.degree=Math.round(degree)
        }else {
            this.degree=-Math.round(degree)
        }
    },
    /**
     * 改变摇杆锁定状态
     * @param e
     */
    change1(e){
        this.rocker_lock=e.checked
        this.rocker_X = this.X_orig;
        this.rocker_Y = this.Y_orig;
        this.degree=0;
        if (e.checked) {
            prompt.showToast({message:"摇杆锁定"})
        }else {
            prompt.showToast({message:"摇杆解锁"})
        }
    },
    /**
     * 改变推杆锁定状态
     * @param e
     */
    change2(e){
        this.speed_lock=e.checked
        this.ap_Y=this.ap_Y_orig
        this.speed_ctrl=0;
        if (e.checked) {
            prompt.showToast({message:"推杆锁定"})
        }else {
            prompt.showToast({message:"推杆解锁"})
        }
    },
    /**
     * 推杆开始移动
     * @param e
     */
    speedMove(e){
        let Y=e.touches[0].globalY-25;
        if (Y>this.ap_Y_orig) {
            Y=this.ap_Y_orig;
        }else if(Y<90){
            Y=90;
        }
        this.ap_Y=Y
        this.speed_ctrl=Math.round((1-((this.ap_Y-90)/120))*1000)
    },
    /**
     * 推杆停止移动
     */
    speedEnd(){
        this.notice_init();
        if (this.speed_lock) {
            this.ap_Y=this.ap_Y_orig;
            this.speed_ctrl=0;
        }
    },

    /**
     * 停止小车命令开始
     */
    stopStart(){
        this.notice_init();
        this.stop_state=true;
        if (this.connect_state) {
            let data=new MessageData();
            data.option="stop"
            BLE.actionJava(data);
        }
    },
    /**
     * 停止小车命令结束
     */
    stopEnd(){
        this.stop_state=false;
        if (this.connect_state) {
            let data=new MessageData();
            data.option="start"
            BLE.actionJava(data);
        }
    },

    /**
     * 跳转蓝牙控制页面
     */
    blue_page(){
        Router.push({
            uri:"pages/blueTooth/blueTooth",
        })
    },
    /**
     * 切换控制模式
     */
    change_car_mode(){
        this.notice_init();
        let data=new MessageData();
        data.option="mod";
        data.code=AUTO_MOD;
        BLE.actionJava(data);
        Router.push({
            uri:"pages/autoDrive/autoDrive",
            params: {
                connect_state:this.connect_state,
            }
        })
    },
    /**
     * 控制信号发送
     */
    car_control(){
        if (this.connect_state&&this.car_init) {
            let data=new MessageData();
            if(!this.stop_state){
                data.option="control"
                let speed=this.speed_ctrl
                if (!this.sign_GO_BACK) {
                    speed=-speed;
                }
                data.speed=speed;
                let degree=this.degree+90
                data.degree=degree;
            }
            BLE.actionJava(data);
        }
    },

    /**
     * action初始化
     * @returns
     */
    initAction(){
        var action = {};
        action.bundleName = 'com.sinan.myapplication';
        action.abilityName = 'com.sinan.myapplication.bleBTServiceAbility';
        return action;
    },
    /**
     * 订阅相关功能初始化
     * @param method
     * @returns
     */
    initActionSubscribe(method){
        var action=this.initAction();
        if (method == "subscribe") {
            action.messageCode = ACTION_MESSAGE_CODE_SUBSCRIBE_USER;
        }else if(method == "unsubscribe"){
            action.messageCode = ACTION_MESSAGE_CODE_UNSUBSCRIBE;
        }
        action.abilityType = ABILITY_TYPE_EXTERNAL;
        action.syncOption = ACTION_SYNC;
        return action;
    },

    /**
     * 调用java实现
     * @param method
     * @param option=''
     */
    async actionJava(method) {
        if(method=="subscribe"){
            var result = await FeatureAbility.subscribeAbilityEvent(this.initActionSubscribe(method),this.notifyHandle);
            var ret = JSON.parse(result);
            if (ret.code == 0) {
                console.info('subscribe success, result:' + result);
            } else {
                console.error('subscribe error, result:' + result);
            }
        }else if(method=="unsubscribe"){
            var result = await FeatureAbility.unsubscribeAbilityEvent(this.initActionSubscribe(method));
            var ret = JSON.parse(result);
            if (ret.code == 0) {
                console.info('unsubscribe success, result: ' + result);
            } else {
                console.error('unsubscribe error, result: ' + result);
            }
        }
    },


    /**
     * javaPA通知处理
     * @param callbackData
     */
    notifyHandle(callbackData){
        var callbackJson = JSON.parse(callbackData).data;
        if(callbackJson.type=="connection"){
            if (callbackJson.num1 == 1) {
                if(!this.connect_state){
                    Prompt.showToast({message:"已连接！"});
                    this.connect_state=true;
                    let data=new MessageData();
                    data.option="mod";
                    data.code=6;
                    BLE.actionJava(data);
                }
            }else {
                if(this.connect_state){
                    Prompt.showToast({message:"连接断开！"});
                    this.connect_state=false;
                    this.RSSI=0;
                }
            }
        }else if (callbackJson.type=="S_S"){
            this.speed=callbackJson.num3;
            let value=callbackJson.num1;
            if (value==1) {
                this.barrier=true;
            }else {
                this.barrier=false;
            }
            this.power=callbackJson.num2;
            this.car_init=true;
        }else if(callbackJson.type=="S_I"){
            this.car_init=false;
            this.comp_init=callbackJson.num1;
        }else if(callbackJson.type=="RSSI"){
            this.RSSI=callbackJson.num1;
        }
    }
}
